import React, { Component } from 'react';
import {
  Col,
  Space,
  Row,
  Form,
  message,
  Button,
  Typography,
  InputNumber,
  Card,
  Radio,
  Tooltip,
} from 'antd';
import {
  DownloadOutlined,
  CheckOutlined,
  ExclamationOutlined,
} from '@ant-design/icons';
import 'antd/dist/antd.css';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import 'moment/locale/zh-cn';
import { getDictionaryLabel } from '../../../rudexRou/OperatesCookie.js';
import { getUrl } from '../../../utils';

import {
  queryMarkingPaper,
  updateAnswerScore,
  saveMarking,
  addMarking,
} from '../../../api/exam';
import '../../../componentCss/component.css';

export default class TakeExam extends Component {
  constructor (props) {
    super(props);
    this.state = {
      confirmLoading: false,
      dataLoading: true,
      subjectList: [],
      examData: null,
      markingPaperData: null,
      subjectData: null,
      submitModal: false,
      unfinishList: [],
      cheat: '0',
      realScore: 0,
    };
  }
  subjectForm = React.createRef();
  getExamPaper = (examDetailId) => {
    queryMarkingPaper({ examDetailId: examDetailId })
      .then((res) => {
        if (res.data.code == 200) {
          const subjectData = res.data.data.questionAnswerPackageList;
          // console.log('subjectData:', subjectData);
          let real = 0;
          for (let i = 0; i < subjectData.length; i++) {
            if (subjectData[i].answer && !subjectData[i].answer.answerKey) {
              message.warning('阅卷包未生成，不能阅卷', 5);
              return getUrl('/TmfsExam/ReadingTask/ExamDetail');
            }
          }
          subjectData.forEach((item) => {
            if (item.answer && item.answer.score > 0) {
              real = real + item.answer.score;
            }
          });

          this.setState(
            {
              subjectData: [],
            },
            () => {
              this.setState({
                dataLoading: false,
                examData: res.data.data,
                subjectData: subjectData,
                realScore: real,
              });
            }
          );
        } else {
          message.error(res.data.message || '试卷信息查询失败', 3);
          getUrl('/TmfsExam/ReadingTask/ExamDetail');
        }
      })
      .catch((err) => {
        message.error('试卷信息查询失败', 3);
        getUrl('/TmfsExam/ReadingTask/ExamDetail');
      });
  };
  showSubmitModal = () => {
    let markingPaperData = JSON.parse(
      sessionStorage.getItem('markingPaperData')
    );
    let subjectData = this.state.subjectData;
    let errMsg = [];
    subjectData.forEach((item, index) => {
      if (
        !item.answer ||
        (!item.answer.score && item.answer.score !== 0) ||
        item.answer.score < 0
      ) {
        errMsg.push(`题目${1 + index}`);
      }
    });
    if (errMsg && errMsg.length) {
      return message.error(errMsg.toString() + ' 未保存得分,不能完成阅卷！', 4);
    } else {
      const data = {
        id: markingPaperData.id,
        cheat: this.state.cheat,
      };
      this.setState({ markingPaperData });
      saveMarking(data).then((res) => {
        if (res.data.code === 200) {
          message.success('阅卷成功');
          getUrl('/TmfsExam/ReadingTask/ExamDetail');
        } else {
          message.error(res.data.message || '阅卷失败');
        }
      });
    }
  };
  hiddenModal = () => {
    this.setState({ submitModal: false, unfinishList: [] });
  };
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag });
  };
  scrollToAnchor = (anchorName) => {
    if (anchorName) {
      // 找到锚点
      const anchorElement = document.getElementById(anchorName);
      // 如果对应id的锚点存在，就跳转到锚点
      if (anchorElement) {
        anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
      }
    }
  };
  componentWillMount () {
    let markingPaperData = JSON.parse(
      sessionStorage.getItem('markingPaperData')
    );
    if (markingPaperData) {
      this.setState({ markingPaperData });
      this.getExamPaper(markingPaperData.id);
    } else {
      getUrl('/TmfsExam/ReadingTask/ExamDetail');
    }
  }
  reInit = (e) => {
    this.getExamPaper(this.state.markingPaperData.id);
  };
  componentDidMount () { }
  componentWillUnmount () { }
  onChange = (e) => {
    this.setState({ cheat: e.target.value });
  };
  callback = (anwser, value) => {
    const subjectData = this.state.subjectData;
    let real = 0;
    subjectData.forEach((item) => {
      if (item.answer && item.answer.id === anwser.id) {
        item.answer.score = value;
      }
      if (item.answer && item.answer.score > 0) {
        real = real + item.answer.score;
      }
    });
    this.setState({
      realScore: real,
    });
  };
  render () {
    return (
      <div style={{ padding: '0px 20px 20px 30px', position: 'relative' }}>
        {this.state.dataLoading ? (
          <div></div>
        ) : (
          <>
            <Row wrap={false}>
              <Col flex='auto'>
                <Row gutter={[20, 20]}>
                  <Col span={24}>
                    <Card style={{ borderColor: '#ddd' }}>
                      <Row wrap={false} gutter={[40]}>
                        <Col>考试名称：{this.state.examData.examName}</Col>
                        <Col>
                          考试语言：
                          {getDictionaryLabel(
                            'language',
                            this.state.examData.language
                          )}
                        </Col>
                        <Col>
                          考试级别：
                          {getDictionaryLabel(
                            'examLevel',
                            this.state.examData.level
                          )}
                        </Col>
                        <Col>考试时长：{this.state.examData.duration} min</Col>
                      </Row>
                    </Card>
                  </Col>
                  {this.state.subjectData.map((item, index) => {
                    return (
                      <Col span={24} key={index + 1}>
                        <div
                          name={'components' + (index + 1)}
                          id={'components' + (index + 1)}
                        >
                          <ExamCard
                            index={index}
                            subjectInfo={item}
                            markingPaperData={this.state.markingPaperData}
                            language={this.state.examData.language}
                            callback={this.callback}
                            reInit={this.reInit}
                          />
                        </div>
                      </Col>
                    );
                  })}
                </Row>
              </Col>
              <Col flex='180px'></Col>
            </Row>
            <Row wrap={false}>
              <Col flex='auto'>
                <Row gutter={[20, 20]}>
                  <Col span={24}>
                    <Card style={{ borderColor: '#ddd', marginTop: '20px' }}>
                      <Row>
                        <Col span={24}>
                          <Typography.Title level={5}>总成绩</Typography.Title>
                        </Col>
                      </Row>
                      <Row>
                        <Col span={24}>
                          <Space size='middle'>
                            总分：
                            <span className='totalScore'>
                              {this.state.examData.totalScore}
                            </span>
                          </Space>
                        </Col>
                      </Row>
                      <Row>
                        <Col span={24}>
                          <Space size='middle'>
                            得分：
                            <span className='totalScore'>
                              {this.state.realScore}
                            </span>
                          </Space>
                        </Col>
                      </Row>
                      <Row>
                        <Col span={24}>
                          <Space size='middle'>
                            是否作弊：
                            <Radio.Group
                              name='radiogroup'
                              defaultValue={0}
                              onChange={this.onChange}
                            >
                              <Radio value={1}>是</Radio>
                              <Radio value={0}>否</Radio>
                            </Radio.Group>
                          </Space>
                        </Col>
                      </Row>
                      <Row>
                        <Col span={24}>
                          <Space size='middle'>
                            是否通过：
                            <span className='totalScore'>
                              {this.state.examData.passScore >
                                this.state.realScore
                                ? '不通过'
                                : '通过'}
                            </span>
                          </Space>
                        </Col>
                      </Row>
                      <Row style={{ marginTop: '20px' }}>
                        <Col span={24}>
                          <Space size='middle'>
                            <Button
                              type='primary'
                              onClick={this.showSubmitModal}
                              loading={this.state.confirmLoading}
                            >
                              完成阅卷
                            </Button>
                          </Space>
                        </Col>
                      </Row>
                    </Card>
                  </Col>
                </Row>
              </Col>
              <Col flex='180px'></Col>
            </Row>
            <div
              style={{
                position: 'fixed',
                top: '134px',
                right: '60px',
                width: '156px',
                border: '1px solid #ddd',
                padding: '24px 10px 10px',
              }}
            >
              <Row gutter={[20, 10]}>
                <Col span={24}>题目列表：</Col>
                {this.state.subjectData.map((item, index) => {
                  return (
                    <Col span={24} key={index + 1}>
                      <a
                        onClick={() =>
                          this.scrollToAnchor('components' + (index + 1))
                        }
                      >
                        <Space>
                          <span>题目{index + 1}</span>

                          {item.answer &&
                            (item.answer.score || item.answer.score === 0) &&
                            item.answer.score > -1 ? (
                            <Tooltip placement='right' title='已阅'>
                              <CheckOutlined style={{ color: '#0f0' }} />
                            </Tooltip>
                          ) : (
                            <Tooltip placement='right' title='未阅'>
                              <ExclamationOutlined style={{ color: '#f00' }} />
                            </Tooltip>
                          )}
                        </Space>
                      </a>
                    </Col>
                  );
                })}
              </Row>
            </div>
          </>
        )}
      </div>
    );
  }
}

class ExamCard extends Component {
  constructor (props) {
    super(props);
    this.state = {
      subjectInfo: this.props.subjectInfo,
      markingPaperData: this.props.markingPaperData,
      fileList: [],
      answer: this.props.subjectInfo.answer,
      tempFilePath: null,
      checkMessage: null,
      checkMessageType: null,
      uploadLoading: false,
      downloadLoading: false,
    };
  }
  answerForm = React.createRef();

  componentWillMount () {
    if (
      !this.state.answer ||
      (this.state.answer &&
        (this.state.answer.answerUrl == '没有上传答案' ||
          this.state.answer.answerKey == '没有上传答案' ||
          this.state.answer.answerUrl == '没有上传答案包' ||
          this.state.answer.answerKey == '没有上传答案包'))
    ) {
      this.setState({
        checkMessage: '考生未上传答案包',
        checkMessageType: 'danger',
      });
    } else if (this.state.answer && !this.state.answer.answerKey) {
      // message.warning('阅卷包未生成，不能阅卷', 3);
      // return getUrl('/TmfsExam/ReadingTask/ExamDetail');
      this.setState({
        checkMessage: '阅卷包未生成',
        checkMessageType: 'warning',
      });
    } else if (
      this.state.answer &&
      this.state.answer.answerUrl &&
      this.state.answer.answerKey
    ) {
      this.setState({
        checkMessage: '阅卷包已生成',
        checkMessageType: 'success',
      });
    }
  }
  componentDidMount () {
    const score = this.state.answer && this.state.answer.score;
    if (score !== -1) {
      this.answerForm.current.setFieldsValue({ score });
    }
    // console.log('componentDidMount:', this.props.subjectInfo);
  }
  downloadFile = () => {
    if (
      !this.state.answer ||
      (this.state.answer &&
        (this.state.answer.answerUrl == '没有上传答案' ||
          this.state.answer.answerKey == '没有上传答案' ||
          this.state.answer.answerUrl == '没有上传答案包' ||
          this.state.answer.answerKey == '没有上传答案包'))
    ) {
      message.warning('考生未上传答案包');
    } else if (this.state.answer && !this.state.answer.answerKey) {
      message.warning('阅卷包未生成');
    } else if (
      this.state.answer &&
      this.state.answer.answerUrl &&
      this.state.answer.answerKey
    ) {
      window.open(this.state.answer.answerUrl);
    }
  };
  downloadClientFile = () => {
    window.open(this.state.subjectInfo.questionPackage);
  }
  downloadServerFile = () => {
    window.open(this.state.subjectInfo.serverPackage);
  }
  saveScore = () => {
    let data = this.answerForm.current.getFieldsValue();
    if (data.score === 0 || data.score) {
      if (this.state.answer && this.state.answer.id) {
        const params = {
          id: this.state.answer.id,
          score: data.score,
        };
        updateAnswerScore(params).then((res) => {
          this.props.callback(this.state.answer, data.score);
          if (res.data.code === 200) {
            message.success(res.data.message);
          } else {
            message.error(res.data.message);
          }
        });
      } else {
        const params = {
          testexamDetailId: this.state.markingPaperData.id,
          testexamQuestionId: this.state.subjectInfo.ttestexamQuestionId,
          score: data.score,
        };
        addMarking(params).then((res) => {
          if (res.data.code === 200) {
            message.success(res.data.message);
          } else {
            message.error(res.data.message);
          }
          this.props.reInit();
        });
      }
    } else {
      message.warning('请填写得分后保存');
    }
  };
  render () {
    return (
      <div>
        <Row wrap={false}>
          <Col flex='auto'>
            <Card style={{ borderColor: '#ddd', borderRight: 'none' }}>
              <Typography.Title level={5}>题目描述</Typography.Title>

              <BraftEditor
                readOnly={true}
                controls={[]}
                contentStyle={{
                  height: '600px',
                }}
                defaultValue={BraftEditor.createEditorState(
                  this.state.subjectInfo.description
                )}
              // value={editorState}
              />
            </Card>
          </Col>
          <Col flex='360px'>
            <Card style={{ borderColor: '#ddd', height: '100%' }}>
              <Typography.Title level={5}>题目信息</Typography.Title>
              <Form>
                <Form.Item label='阅卷包下载'>
                  <Button
                    loading={this.state.downloadLoading}
                    onClick={this.downloadFile}
                    icon={<DownloadOutlined />}
                  >
                    点击下载
                  </Button>
                  <div>
                    <Typography.Text type={this.state.checkMessageType}>
                      {this.state.checkMessage}
                    </Typography.Text>
                  </div>
                </Form.Item>
                <Form.Item label='题目包下载'>
                  <Button
                    loading={this.state.downloadLoading}
                    onClick={this.downloadClientFile}
                    icon={<DownloadOutlined />}
                  >
                    点击下载
                  </Button>
                </Form.Item>
                <Form.Item label='服务包下载'>
                  <Button
                    loading={this.state.downloadLoading}
                    onClick={this.downloadServerFile}
                    icon={<DownloadOutlined />}
                  >
                    点击下载
                  </Button>
                </Form.Item>
              </Form>
              <Typography.Title level={5} style={{ marginTop: '30px' }}>
                录入成绩
              </Typography.Title>
              <Form name='answerForm' ref={this.answerForm}>
                <Form.Item label='题目名称'>
                  {this.state.subjectInfo.title}
                </Form.Item>
                <Form.Item label='题目分值'>
                  {this.state.subjectInfo.score}
                </Form.Item>
                <Form.Item label='得分' name='score'>
                  <InputNumber
                    min={0}
                    max={this.props.subjectInfo.score}
                    precision={0}
                  />
                </Form.Item>
              </Form>
              <Button type='primary' onClick={() => this.saveScore()}>
                保存
              </Button>
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}
